﻿using SuporeSliplampApp.Util;
using System;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using LibVLCSharp.Shared;
using System.Windows.Threading;
using SuporeSliplampApp.Models;
using System.Windows.Input;
using System.ComponentModel;

namespace SuporeSliplampApp.Views
{
    /// <summary>
    /// VideoView.xaml 的交互逻辑
    /// </summary>
    public partial class VideoView : Window
    {
        private LibVLC _libVLC;
        private Media _media;
        private DispatcherTimer _timer;
        private bool _isDragging;

        public VideoView(string videoPath)
        {
            InitializeComponent();
            InitializeVLC(videoPath);
        }




        private void InitializeVLC(string path)
        {
            Core.Initialize();

            //string vlcLibDirectory = AppDomain.CurrentDomain.BaseDirectory;

            var options = new string[]
            {
            "--avcodec-hw=dxva2",
            "--deinterlace=auto",
            "--network-caching=500",   
            "--clock-synchro=0",
            "--vout=wgl",
            };

            _libVLC = new LibVLC(options);
            //videoView.MediaPlayer = new LibVLCSharp.Shared.MediaPlayer(_libVLC);

            var mediaPlayer = new LibVLCSharp.Shared.MediaPlayer(_libVLC);

            // 将 MediaPlayer 绑定到 videoView
            videoView.MediaPlayer = mediaPlayer;

            LoadMedia(path);
            SetupTimer();

            mediaPlayer.PositionChanged += MediaPlayer_PositionChanged;

            mediaPlayer.Playing += (sender, args) =>
            {
                Dispatcher.Invoke(() =>
                {
                    var duration = videoView.MediaPlayer.Length; 
                    totalTimeText.Text = FormatTime(duration);
                });
            };

        }

        private void LoadMedia(string path) 
        {
            _media = new Media(_libVLC, new Uri(path));
            _media.AddOption(":no-mediacodec-dr");
            _media.AddOption(":avcodec-skiploopfilter=1");

            videoView.MediaPlayer.Media = _media;
            videoView.MediaPlayer.Play(_media);
            SetPaused(true);
        }


        private void SetupTimer()
        {   
            _timer = new DispatcherTimer
            {
                Interval = TimeSpan.FromMilliseconds(100)
            };
            _timer.Tick += (s, e) => UpdateProgress();
            _timer.Start();
        }

        private void UpdateProgress()
        {
            if (_isDragging || videoView.MediaPlayer == null || !videoView.MediaPlayer.IsPlaying ) return;

            try
            {
                var position = videoView.MediaPlayer.Position;
                var time = videoView.MediaPlayer.Time;

                videoSlider.Value = position;
                currentTimeText.Text = FormatTime(time);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"更新进度失败: {ex.Message}");
            }
        }

        private string FormatTime(long ms)
        {
            var ts = TimeSpan.FromMilliseconds(ms);
            return ts.ToString(@"mm\:ss");
        }


        private void MediaPlayer_PositionChanged(object sender, MediaPlayerPositionChangedEventArgs e)
        {
            // 避免进入 Ended 状态
            if (e.Position >= 0.999f)
            {
                Dispatcher.Invoke(() =>
                {
                    if (videoView.MediaPlayer.IsPlaying)
                    {
                        videoView.MediaPlayer.SetPause(true);
                        videoView.MediaPlayer.Position = 0.999f;
                        playPauseButton.Content = "\ue62d";
                    }
                });
            }
        }


        private void PlayPause_Click(object sender, RoutedEventArgs e)
        {
            var mp = videoView.MediaPlayer;

            if (videoView.MediaPlayer.IsPlaying)
            {
                SetPaused(true);
                playPauseButton.Content = "\ue62d";
            }
            else
            {
                if (mp.Position >= 0.999f)
                {
                    mp.Position = 0f;
                }
                SetPaused(false);
                playPauseButton.Content = "\ue6cf";
            }
        }

        private void SetPaused(bool paused)
        {
            if (paused)
            {
                videoView.MediaPlayer.SetPause(true);
            }
            else
            {
                if (videoView.MediaPlayer.State == VLCState.Ended)
                {
                    videoView.MediaPlayer.Stop();
                    videoView.MediaPlayer.Position = 0f; 
                }
                videoView.MediaPlayer.Play();
            }
        }

        private void Fastforward_Click(object sender, RoutedEventArgs e)
        {
            var mp = videoView.MediaPlayer;
            var newTime = mp.Time + 5000;

            // 限制最大时间在总长度的99.9%
            var maxTime = (long)(mp.Length * 0.999);
            if (newTime > maxTime)
                newTime = maxTime;

            mp.Time = newTime;
            mp.SetPause(false);
        }

        private void Rewind_Click(object sender, RoutedEventArgs e)
        {
            videoView.MediaPlayer.Time -= 5000;
            videoView.MediaPlayer.SetPause(false);
        }

        // 进度条控制
        private void videoSlider_PreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            _isDragging = true;
            videoView.MediaPlayer.SetPause(true);
        }

        private void videoSlider_PreviewMouseUp(object sender, MouseButtonEventArgs e)
        {
            _isDragging = false;
            var position = videoSlider.Value;

            if (position >= 0.999)
                position = 0.999;

            videoView.MediaPlayer.Position = (float)videoSlider.Value;
            videoView.MediaPlayer.SetPause(false);
        }

        public static event EventHandler<ListControlModel> cutDelegate;
        private void Cut_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                string timestamp = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                string uniqueSuffix = DateTime.UtcNow.Ticks.ToString().Substring(10, 3); 
                string fileName = $"{timestamp}_{uniqueSuffix}_cut.bmp";

                var savePath = System.AppDomain.CurrentDomain.BaseDirectory + fileName;

                videoView.MediaPlayer.TakeSnapshot(0, savePath, 0, 0);

                var model = new ListControlModel { ImgPath = savePath , Name = fileName };
                cutDelegate?.Invoke(this, model);
            }
            catch (Exception ex)
            {

            }
        }

        private void Cancel_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            CleanupMediaPlayer();
            base.OnClosing(e);
        }

        private void CleanupMediaPlayer()
        {
            if (videoView.MediaPlayer != null)
            {
                if (videoView.MediaPlayer.IsPlaying)
                {
                    videoView.MediaPlayer.Stop();
                }

                videoView.MediaPlayer.Dispose();
                videoView.MediaPlayer = null;

                if (_media != null)
                {
                    _media.Dispose();
                    _media = null;
                }
            }

            if (_libVLC != null)
            {
                _libVLC.Dispose();
                _libVLC = null;
            }

            if (_timer != null)
            {
                _timer.Stop();
                _timer = null;
            }

        }

    }
}
